package com.zhiche.lisa.bms.service.price.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.zhiche.lisa.bms.dao.mapper.price.PriceFiRateMapper;
import com.zhiche.lisa.bms.dao.model.price.PriceFiRate;
import com.zhiche.lisa.bms.service.price.PriceFiRateService;
import com.zhiche.lisa.core.supports.BaseException;
import com.zhiche.lisa.core.utils.Account.AccountUtil;
import com.zhiche.lisa.core.utils.Account.JwtAccountVO;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * <p>
 * 财务系数设置 服务实现类
 * </p>
 *
 * @author qichao
 * @since 2018-08-31
 */
@Service
public class PriceFiRateServiceImpl extends ServiceImpl<PriceFiRateMapper, PriceFiRate> implements PriceFiRateService {
    private static final Logger LOGGER = LoggerFactory.getLogger(PriceFiRateService.class);

    /**
     * 财务系数分页查询
     *
     * @params page
     */
    @Override
    public Page<PriceFiRate> priceFiRateLinePage(Page<PriceFiRate> page) {
        try {
            EntityWrapper<PriceFiRate> ew = buildCondition(page.getCondition());
            List<PriceFiRate> list = baseMapper.selectPage(page, ew);
            page.setRecords(list);
            return page;
        } catch (BaseException e) {
            LOGGER.error("PriceFiRateServiceImpl.priceFiRatePage:" + e.getMessage());
            throw e;
        } catch (Exception e) {
            LOGGER.error("PriceFiRateServiceImpl.priceFiRatePage:" + e.getMessage());
            throw new BaseException("获取财务系数信息失败");
        }
    }

    /**
     * 新增财务系数
     *
     * @param priceFiRate
     */
    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public void insertPriceRate(PriceFiRate priceFiRate) {
        try {
            if (Objects.isNull(priceFiRate.getLspId())) throw new BaseException("请输入承运商");
            if (priceFiRate.getEffectiveDate() == null) throw new BaseException("请输入生效日期");
            if (Objects.isNull(priceFiRate.getFiRate())) throw new BaseException("请输入财务系数");
            JwtAccountVO jwtAccountVO = AccountUtil.getAccountInfoFromSecurityContext();
            if (Objects.isNull(jwtAccountVO)) throw new BaseException("未获取登录信息");
            //判断该承运商是否存在
            EntityWrapper<PriceFiRate> ew = new EntityWrapper<>();
            ew.eq("lsp_id", priceFiRate.getLspId());
            ew.ge("effective_date", priceFiRate.getEffectiveDate());
            List<PriceFiRate> list = this.selectList(ew);
            if (CollectionUtils.isEmpty(list)) {
                EntityWrapper<PriceFiRate> entityWrapper = new EntityWrapper<>();
                entityWrapper.eq("lsp_id", priceFiRate.getLspId());
                entityWrapper.isNull("invalid_date");
                entityWrapper.orderBy("effective_date ", false);
                List<PriceFiRate> list1 = this.selectList(entityWrapper);
                if (!CollectionUtils.isEmpty(list1)) {
                    list1.get(0).setInvalidDate(priceFiRate.getEffectiveDate());
                    this.updateById(list1.get(0));
                }
                //绑定剩余信息
                priceFiRate.setCreator(new Long(jwtAccountVO.getAccountId()));
                priceFiRate.setGmtCreate(new Date());
                priceFiRate.setTenantId(new Long(jwtAccountVO.getTenantId()));
                this.insert(priceFiRate);
            } else {
                throw new BaseException("新增财务系数生效日期在已有财务系数失效日期之内");
            }
        } catch (BaseException e) {
            LOGGER.error("PriceFiRateServiceImpl.insertPriceRate:" + e.getMessage());
            throw e;
        } catch (Exception e) {
            LOGGER.error("PriceFiRateServiceImpl.insertPriceRate:" + e.getMessage());
            throw new BaseException("新增财务系数失败");
        }

    }

    private EntityWrapper<PriceFiRate> buildCondition(Map<String, Object> condition) {
        EntityWrapper<PriceFiRate> ew = new EntityWrapper<>();
        ew.orderBy("gmt_create desc, id desc");
        if (!Objects.equals(condition, null)) {
            for (Map.Entry<String, Object> entry : condition.entrySet()) {
                if (Objects.nonNull(entry.getValue())) {
                    if (!StringUtils.isEmpty(String.valueOf(entry.getValue()))) {
                        if (entry.getKey().equals("lspName") && StringUtils.isNoneBlank(entry.getValue().toString())) {
                            //承运商名称查询
                            ew.like("lsp_name", String.valueOf(entry.getValue()));
                        }
                        if (entry.getKey().equals("effectiveDate") && StringUtils.isNoneBlank(entry.getValue().toString())) {
                            ew.ge("effective_date", String.valueOf(entry.getValue()));
                        }
                        if (entry.getKey().equals("invalidDate") && StringUtils.isNoneBlank(entry.getValue().toString())) {
                            ew.le("effective_date", String.valueOf(entry.getValue()));
                        }
                    }
                }

            }
        }
        ew.orderBy("lsp_id");
        return ew;
    }

    /**
     * 根据承运商ID查询财务系数
     *
     * @param lspId
     * @return
     */
    @Override
    public PriceFiRate queryPriceFiRateById(Long lspId) {
        if (lspId == null) {
            throw new BaseException("承运商Id为空");
        }
        EntityWrapper ew = new EntityWrapper<>();
        ew.eq("lsp_id", lspId);
        ew.le("effective_date", new Date());
        ew.andNew().gt("invalid_date", new Date()).or().isNull("invalid_date");
        List<PriceFiRate> list = baseMapper.selectListNoTenant(ew);
        if (CollectionUtils.isEmpty(list)) {
            return null;
        }
        return list.get(0);
    }
}

